package com.basedefence;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import org.andengine.engine.Engine;
import org.andengine.engine.Engine.UpdateThread;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.modifier.IModifier.DeepCopyNotSupportedException;
import org.andengine.util.modifier.IModifier.IModifierListener;

import com.basedefence.models.AnimatedGameObject;
import com.basedefence.models.BaseRocket;
import com.basedefence.models.DefaultRocket;
import com.basedefence.models.GameObject;
import com.basedefence.models.GamePool;
import com.basedefence.models.IGameObject;

import android.view.MotionEvent;

//import android.app.Activity;
//import android.os.Bundle;
//
//public class BaseDefenceActivity extends Activity {
//    /** Called when the activity is first created. */
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
//    }
//}

public class BaseDefenceActivity extends SimpleBaseGameActivity
{
	private static boolean isInGame;
	private AnimatedSprite rocket;

	private static BaseDefenceActivity instance = null;
	private ITextureRegion mBackgroundTextureRegion,mBaseTextureRegion;
	public static BaseDefenceActivity getInstance()
	{
		return instance;
	}
//	AnimatedSprite rocket;
	ITexture rocketTexture;
	public static int m_nScrW;
	public static int m_nScrH;
	
	private Camera mCamera;

//	private void AddRocketPair(E3Scene scene)
//	{
////		AddNewRocket(scene, 50, 50, 100, m_nScrW / 2, 400);
////		AddNewRocket(scene, m_nScrW - 50, 50, 100, m_nScrW / 2, 400);
//		AddNewRocket(scene, 50, 50, 100, baseObject.getCenterX(), baseObject.getCenterY());
//		AddNewRocket(scene, m_nScrW - 50, 50, 100, baseObject.getCenterX(), baseObject.getCenterY());
//	}

//	private void AddBase (E3Scene scene) 
//	{
//		AnimatedSprite baseSpr = SpriteLoader.getAnimation("base.png", 0);
//		
//		int cX = m_nScrW / 2;
//		int cY = m_nScrH - 10;
//		
//		baseSpr.move((int)(cX - baseSpr.getWidthScaled() / 2), (int)(cY - baseSpr.getHeightScaled()));
//		baseSpr.scale(0.45f, 0.35f);
//		
//		baseObject = new Base();
//		baseObject.setSprite(baseSpr);
//		baseObject.setCenter(cX, cY);
//		
//		scene.getTopLayer().add(baseSpr);
//	}

//	private void AddNewRocket (E3Scene scene, int x, int y, int speed, int targetX, int targetY)
//	{
//		AnimatedSprite rocketSprite = SpriteLoader.getAnimation("rocket.png", 0);
//		int rCenterX = (int) (rocketSprite.getWidthScaled()  / 2);
//		int rCenterY = (int) (rocketSprite.getHeightScaled() / 2);
//
//		rocketSprite.move(x - rCenterX, y - rCenterY);
//		rocketSprite.setRotationCenter(rCenterX, rCenterY);
//		rocketSprite.scale(0.5f, 0.5f);
//		
//		Rocket rocket = new Rocket();
//		rocket.setSprite(rocketSprite);
//		rocket.setSpeed(speed);
//		
//		Vector2 v = new Vector2(targetX - rocketSprite.getRealX(), targetY - rocketSprite.getRealY());
//		rocket.setDirection(v.nor(), true);
//		
//		rockets.add(rocket);
//		
//		scene.getTopLayer().add(rocketSprite);
//	}

//	public void onUpdateScene(E3Scene scene, long elapsedTime) {
//		if (Debug.useStaticTime)
//			elapsedTime = 30;
//				
//		for (int i = rockets.size() - 1; i > 0; i--)
//		{
//			Rocket currRocket = rockets.get(i);
//			if (currRocket.getState() == RocketState.died)
//				RemoveRocket(scene, currRocket);
//		}
//		
//		for (Rocket currRocket : rockets) {
//			currRocket.update(elapsedTime);
//			
//			for (Rocket rocketToCheck : rockets) {
//				if (rocketToCheck.getState() == RocketState.idle && currRocket.getState() == RocketState.idle)
//				{
//					if (rocketToCheck != currRocket && rocketToCheck.getSprite().collidesWith(currRocket.getSprite()))
//					{
//						rocketToCheck.destroy();
//						currRocket.destroy();
//						AddRocketPair(scene);
//						return;
//					}
//				}
//			}
//		}
//	}
	
//	private void RemoveRocket(E3Scene scene, Rocket currRocket) {
//		rockets.remove(currRocket);
//		currRocket.getSprite().hide();
//		scene.getTopLayer().remove(currRocket.getSprite());
//	}

	public void onStop() 
	{
		isInGame = false;
		super.onStop();
		SpriteLoader.unloadGameObject("rocket.png");
		TextureManager.unloadTexture("rocket.png");
		SpriteLoader.unloadGameObject("base.png");
		TextureManager.unloadTexture("base.png");
		SpriteLoader.unloadGameObject("back_tile.jpg");
	}
	
//	public boolean onSceneTouchEvent (final E3Scene scene, final MotionEvent motionEvent) 
//	{
//		if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) 
//		{
//			int x = getTouchEventX(scene, motionEvent);
//			int y = getTouchEventY(scene, motionEvent);
//			
//			Drawable obj;
//			if ((obj = scene.findDrawableAt(x, y)) != null) 
//			{
//				AnimatedSprite spr = (AnimatedSprite)obj;
//				Rocket currRocket = getRocket(spr);
//				if (currRocket != null && !currRocket.wasTapped)
//				{
//					if (currRocket.getDirectionX() < 0)
//						currRocket.addAngle(20);
//					else
//						currRocket.addAngle(-20);
//					currRocket.wasTapped = true;
//				}
//			}
//		}
//		
//		return false;
//	}

	@Override
	public EngineOptions onCreateEngineOptions() {
		instance = this;
		m_nScrH = getResources().getDisplayMetrics().heightPixels;
		m_nScrW = getResources().getDisplayMetrics().widthPixels;
		this.mCamera = new Camera(0, 0, m_nScrW, m_nScrH);

		final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(m_nScrW, m_nScrH), this.mCamera);
		engineOptions.getAudioOptions().setNeedsSound(true);
		engineOptions.setUpdateThread(startGameThread());
		return engineOptions;
	}

	@Override
	protected void onCreateResources() {
//		rocketTexture = new TiledTexture("rocket.png", 201, 272, this);
		if (SpriteLoader.getAnimatedGameObject("rocket.png",GameObject.OBJECT_TYPE.DEF_ROCKET) == null)
			SpriteLoader.loadAnimatedGameObject(mEngine,"rocket.png",5,1);
		if (SpriteLoader.getGameObject("base.png") == null)
			SpriteLoader.loadGameObject(mEngine,"base.png");
		if (SpriteLoader.getGameObject("back_tile.jpg") == null)
			SpriteLoader.loadGameObject(mEngine,"back_tile.jpg");
	}
	
	private UpdateThread startGameThread()
	{
		isInGame = true;
		UpdateThread thread = new UpdateThread(){

			@Override
			public void setEngine(Engine pEngine) {
				super.setEngine(pEngine);
			}

			@Override
			public void run() {
				super.run();
			}

			@Override
			public void postRunnable(Runnable pRunnable) {
				super.postRunnable(pRunnable);
			}
			
		};
		return thread;
//		return new Runnable() {
//			
//			@Override
//			public void run() {
//				long timeTmp = System.currentTimeMillis();
//				while(isInGame)
//				{
//					try {
//						GamePool.doUpdate(timeTmp - System.currentTimeMillis());
//						Thread.sleep(100);
//					} catch (InterruptedException e) {
//						isInGame = false;
//						e.printStackTrace();
//					}
//				}
//			}
//		};
	}

	@Override
	public void onBackPressed() {
		isInGame = false;
		super.onBackPressed();
	}

	@Override
	protected Scene onCreateScene() {
		final Scene scene = new Scene();
		IGameObject tmp = SpriteLoader.getGameObject("back_tile.jpg",m_nScrW,m_nScrH,0, 0);
		GamePool.addGameObject(tmp);
		scene.attachChild((GameObject)tmp);
		tmp = SpriteLoader.getGameObject( "base.png",m_nScrW/2,m_nScrH/6,(m_nScrW - m_nScrW/2)/2,m_nScrH - m_nScrH/6);
		GamePool.addGameObject(tmp);
		scene.attachChild((GameObject)tmp);
		BaseRocket rocket = (BaseRocket) SpriteLoader.getAnimatedGameObject("rocket.png",GameObject.OBJECT_TYPE.DEF_ROCKET);
		rocket.animate(100);
//		GamePool.addGameObject(rocket);
//		scene.attachChild((AnimatedGameObject)rocket);
//		scene.registerTouchArea(rocket);
		rocket = (BaseRocket) SpriteLoader.getAnimatedGameObject("rocket.png",GameObject.OBJECT_TYPE.DEF_ROCKET);
		rocket.setPosition(m_nScrW/2,0);
		rocket.animate(100);
		GamePool.addGameObject(rocket);
		scene.attachChild((AnimatedGameObject)rocket);
		scene.registerEntityModifier(new GamePool());
		scene.registerTouchArea(rocket);
		return scene;
	}

}